<!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta charset="UTF-8">
    <title>使用$watch监视service值变化</title>
</head>
<body>
<fieldset>
    <legend>
        ctrl1
    </legend>
    <div ng-controller="Ctrl1"  >
        请输入：<input type="text" ng-model="inputText" ng-change="change()" />

        <p>输入的是：{{person1.name}}</p>


    </div>
</fieldset>

<fieldset>
    <legend>
        ctrl2
    </legend>
<div ng-controller="Ctrl2" >

    <p>{{person2.name}}</p>

</div>
</fieldset>
</body>
<script src="../js/angular.min.js"></script>
<script>

    var app = angular.module('myApp', []);

    app.factory("MyService", function () {
                var service = {};
                service.person = {
                    name: "tom"
                };
                return service;
            }
    );
    app.controller("Ctrl1", function ($scope, MyService) {
        $scope.inputText="";
        $scope.person1 ={name:MyService.person.name};
        $scope.service=MyService;
        $scope.$watch('service',function (newV,oldV) {
            if(newV!=oldV){
                $scope.person1.name=MyService.person.name;
            }
        },true);
        $scope.change = function () {
            MyService.person.name = $scope.inputText;
        };
    });
    app.controller("Ctrl2", function ($scope, MyService) {
        $scope.service=MyService;
        $scope.person2 ={name:MyService.person.name};
        $scope.$watch('service',function (newV,oldV) {
            if(newV!=oldV) {
                $scope.person2 = {name: MyService.person.name};
            }
        },true);

    });
</script>
</body>
</html>